package net.joyphper.commons.security;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.joyphper.commons.Constants;
import net.joyphper.commons.utils.Tools;

public class SidCookie {
	/**
	 * 设置用户验证的sid的cookie值
	 * @param response 请求应答的主体
	 * @param primaryDomain 系统运行的主域名，也就是 cookie作用域
	 */
	public static String setSidCookie(HttpServletResponse response,String primaryDomain) {
		String sid = Tools.getUUID();
		
		StringBuilder sb = new StringBuilder(Constants.USER_COOKIE_SID+"="+sid+";");
		if(!Tools.isEmpty(primaryDomain)){
			sb.append("domain="+primaryDomain+";");
		}
		sb.append("path=/;");
		sb.append("HttpOnly");
		
		//使用会话cookie进行权限验证
		response.setHeader("SET-COOKIE",sb.toString());
		
		return sid;
	}
	
	/**
	 * 读取用户验证的sid值
	 * @param request
	 * @return
	 */
	public static String getSidCookie(HttpServletRequest request) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {

			for (Cookie c : cookies) {
				
				if (c.getName().equalsIgnoreCase(Constants.USER_COOKIE_SID)) {
					value = c.getValue();
					return value;
				}
			}
		}
		return value;
	}
}
